import os

import yaml
from appium import webdriver

from app.base_page import BasePage
from app.main_page import MainPage


class App(BasePage):
    _udid = os.getenv("udid")
    _port = os.getenv("port")

    # 启动app
    def start_app(self):
        if self.driver is None:
            caps = yaml.safe_load(open("../app/caps.yaml", encoding="utf-8"))["caps"]
            if self._udid is not None and self._port is not None:
                caps["udid"] = self._udid
                self.driver = webdriver.Remote(f"http://127.0.0.1:{self._port}/wd/hub", caps)
            else:
                self.driver = webdriver.Remote("http://127.0.0.1:4723/wd/hub", caps)
            self.driver.implicitly_wait(5)
            self.driver.launch_app()
        else:
            self.driver.launch_app()
        return self

    def restart_app(self):
        self.driver.quit()
        self.driver.launch_app()
        return self

    def stop_app(self):
        self.driver.quit()

    def goto_main(self):
        return MainPage(self.driver)
